import Vue from 'vue'
import Vuex from 'vuex'
import {getRequest} from '../utils/api'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { Notification } from 'element-ui';

Vue.use(Vuex);

const now = new Date();

const store = new Vuex.Store({
  state: {
    routes: [],
    sessions:{},
    admins: [],
    currentAdmin: JSON.parse(window.sessionStorage.getItem('user')),
    currentSession: null,
    filterKey:'',
    stomp: null,
    isDot: {}
  },

  mutations: {
    initRoutes(state, payload){
      state.routes = payload;
    },
    changeCurrentSession (state, currentSession) {
      // console.log(currentSession);
			state.currentSession = currentSession;
      Vue.set(state.isDot, state.currentAdmin.username+'#'+state.currentSession.username, false)
		},
		addMessage (state, msg) {
			let mss = state.sessions[state.currentAdmin.username+'#'+msg.to];
      if(!mss){ 
        // 不存在这个会话时，初始化一个数组
        // state.sessions[state.currentAdmin.username+'#'+msg.to] = []
        // 让Vue监听到state.sessions的变化，否则监听不到，不会动态变化
        Vue.set(state.sessions, state.currentAdmin.username+'#'+msg.to, []);
      }// 存在，push消息进这个数组
      state.sessions[state.currentAdmin.username+'#'+msg.to].push({
				content:msg.content,
				date: new Date(),
				self: !msg.notSelf //防止 admin#admin 的情况
			})
		},
		INIT_DATA (state) {
      // 浏览器本地的历史聊天记录,数据持久化
		  let data = localStorage.getItem('vue-chat-session');
		  //console.log(data)
		  if (data) {
			  state.sessions = JSON.parse(data);
		  }
		},
    INIT_ADMINS(state, data){
      state.admins = data;
    },
    INIT_ISDOT (state) {
      // 将红点数据持久化
		  let data = localStorage.getItem('vue-chat-session-dot');
		  //console.log(data)
		  if (data) {
			  state.isDot = JSON.parse(data);
		  }
		},
    // 修改用户信息后更新右上角的用户信息
    INIT_ADMIN(state, admin){
      state.currentAdmin = admin
    }
  },

  actions: {
    initData (context) {
      context.commit('INIT_DATA');
      context.commit('INIT_ISDOT');
      getRequest('/chat/').then(resp=>{
        if(resp){
          context.commit('INIT_ADMINS', resp.obj)
        }
      })
    },
    connect(context){
      context.state.stomp = Stomp.over(new SockJS('/wsyeb/ep'));
      // 因为使用JWT令牌，所以要身份验证
      let token = window.sessionStorage.getItem('tokenStr')
      context.state.stomp.connect({'Auth-Token': token}, success=>{
        //订阅消息
        context.state.stomp.subscribe('/user/queue/chat', msg=>{
          // 接收方存储聊天记录，from和to需要调换位置
          // console.log(msg.body);
          let receiveMsg = JSON.parse(msg.body);
          if(!context.state.currentSession || receiveMsg.from != context.state.currentSession.username){
            Notification({
              title: `管理员 ${receiveMsg.fromNickName} 发来消息`,
              message: receiveMsg.content.length>10?receiveMsg.content.substr(0,10):receiveMsg.content,
              position: 'bottom-right'
            });
            Vue.set(context.state.isDot, context.state.currentAdmin.username+'#'+receiveMsg.from, true)
          }
          receiveMsg.notSelf = true;
          receiveMsg.to = receiveMsg.from; //admin发给wang，wang接收消息并存入sessions：wang#admin
          context.commit('addMessage', receiveMsg)
        })
      },error=>{
        console.log(error);
      })
    }
  }
});

// 聊天记录
store.watch(function (state) {
  return state.sessions
},function (val) {
  console.log('CHANGE: ', val);
  localStorage.setItem('vue-chat-session', JSON.stringify(val));
},{
  deep:true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})

// 红点
store.watch((state)=>{
  return state.isDot;
}, (val)=>{
  localStorage.setItem('vue-chat-session-dot',JSON.stringify(val))
},{
  deep: true
})

export default store;